package org.rpis5.chapters.chapter_07.r2dbs;

import io.r2dbc.postgresql.PostgresqlConnectionConfiguration;
import io.r2dbc.postgresql.PostgresqlConnectionFactory;
import io.r2dbc.spi.ConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.r2dbc.core.DatabaseClient;
import org.springframework.data.r2dbc.core.DefaultReactiveDataAccessStrategy;
import org.springframework.data.r2dbc.core.ReactiveDataAccessStrategy;
import org.springframework.data.r2dbc.dialect.MySqlDialect;
import org.springframework.data.r2dbc.repository.support.R2dbcRepositoryFactory;

/**
 * @author Oliver Gierke
 */
@Configuration
class InfrastructureConfiguration {

    //@Bean
    BookRepository customerRepository2(PostgresqlConnectionFactory factory) {
        DatabaseClient txClient =
                DatabaseClient.builder()
                        .connectionFactory(factory)
                        .build();
        ReactiveDataAccessStrategy accessStrategy = new DefaultReactiveDataAccessStrategy(MySqlDialect.INSTANCE);
        return new R2dbcRepositoryFactory(txClient, accessStrategy)
                .getRepository(BookRepository.class);
    }

    @Bean
    BookRepository customerRepository(R2dbcRepositoryFactory factory) {
        return factory.getRepository(BookRepository.class);
    }

    @Bean
    R2dbcRepositoryFactory repositoryFactory(DatabaseClient client) {
        ReactiveDataAccessStrategy accessStrategy = new DefaultReactiveDataAccessStrategy(MySqlDialect.INSTANCE);
        return new R2dbcRepositoryFactory(client, accessStrategy);
    }

    @Bean
    DatabaseClient databaseClient(ConnectionFactory factory) {
        return DatabaseClient.builder()
                .connectionFactory(factory)
                .build();
    }

    @Bean
    PostgresqlConnectionFactory connectionFactory(DatabaseLocation databaseLocation) {

        PostgresqlConnectionConfiguration config = PostgresqlConnectionConfiguration.builder()
                .host(databaseLocation.getHost())
                .port(databaseLocation.getPort())
                .database(databaseLocation.getDatabase())
                .username(databaseLocation.getUser())
                .password(databaseLocation.getPassword())
                .build();

        return new PostgresqlConnectionFactory(config);
    }
}
